import type { Result } from 'ahooks/lib/useRequest/src/types'
import { create } from 'zustand'

import { IWaybillInfo } from './interface'

export type TRequest = Result<IWaybillInfo, []>

export interface IStore {
  loading: boolean
  waybillInfo: IWaybillInfo | null | undefined
  request?: TRequest
  getData: () => void
  setWaybillInfo: (val: Partial<IWaybillInfo> | ((prevVal: IWaybillInfo | null | undefined) => IWaybillInfo)) => void
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    loading: false,
    waybillInfo: null,
    getData: () => {
      get().request?.run()
    },
    setWaybillInfo: val => {
      set(prev => {
        if (!prev.waybillInfo) return prev
        return {
          waybillInfo: {
            ...prev.waybillInfo,
            ...(typeof val === 'function' ? val(prev.waybillInfo) : val),
          },
        }
      })
    },
  }
})
